import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class StorageUtils {

  static Future<void> save(String key, Object object) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String jsonString = jsonEncode(object);
    await prefs.setString(key, jsonString);
  }

  static Future<T?> get<T>(String key, T Function(Map<String, dynamic>) fromJson) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String? jsonString = prefs.getString(key);
    if (jsonString == null) {
      return null;
    }
    final Map<String, dynamic> jsonMap = jsonDecode(jsonString);
    return fromJson(jsonMap);
  }
  
  // 保存列表数据
  static Future<void> saveList<T>(String key, List<T> list, Map<String, dynamic> Function(T) toJson) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final List<Map<String, dynamic>> jsonList = list.map((item) => toJson(item)).toList();
    final String jsonString = jsonEncode(jsonList);
    await prefs.setString(key, jsonString);
  }
  
  // 获取列表数据
  static Future<List<T>> getList<T>(String key, T Function(Map<String, dynamic>) fromJson) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String? jsonString = prefs.getString(key);
    if (jsonString == null) {
      return [];
    }
    final List<dynamic> jsonList = jsonDecode(jsonString);
    return jsonList.map<T>((item) => fromJson(item)).toList();
  }
  
  // 检查键是否存在
  static Future<bool> exists(String key) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.containsKey(key);
  }
  
  // 删除键
  static Future<bool> remove(String key) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.remove(key);
  }
}
